package v1

import (
	"net/http"
	"strconv"

	"gitee.com/colzry/gin-postgres/model"
	"gitee.com/colzry/gin-postgres/utils"
	"gitee.com/colzry/gin-postgres/utils/errmsg"
	"gitee.com/colzry/gin-postgres/utils/validator"
	"github.com/gin-gonic/gin"
)

func AddUser(c *gin.Context) {
	var user model.User
	var msg string
	var validCode int
	_ = c.ShouldBindJSON(&user)

	msg, validCode = validator.Validate(&user)
	if validCode != errmsg.SUCCESS {
		c.JSON(
			http.StatusOK, gin.H{
				"code":  validCode,
				"message": msg,
			},
		)
		c.Abort()
		return
	}

	code := model.CheckUser(user.Username)
	if code == errmsg.SUCCESS {
		code = model.CreateUser(&user)
	}

	c.JSON(
		http.StatusOK, gin.H{
			"code":  code,
			"message": errmsg.GetErrMsg(code),
		},
	)
}

func GetUserInfo(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	maps := make(map[string]interface{})
	user, code := model.GetUser(id)
	maps["username"] = user.Username
	maps["gender"] = user.Gender
	maps["age"] = user.Age
	c.JSON(
		http.StatusOK, gin.H{
			"code":   code,
			"data":     maps,
			"total":    1,
			"messages": errmsg.GetErrMsg(code),
		},
	)
}

func GetUsers(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	pageNum, _ := strconv.Atoi(c.Query("pageNum"))

	if pageSize == 0 {
		pageSize = utils.PageSize
	}
	if pageNum == 0 {
		pageNum = 1
	}

	data, total := model.GetUsers(pageSize, pageNum)
	c.JSON(
		http.StatusOK, gin.H{
			"code":  errmsg.SUCCESS,
			"data":    data,
			"total":   total,
			"message": errmsg.GetErrMsg(errmsg.SUCCESS),
		},
	)
}

func DeleteUser(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))

	code := model.DeleteUser(id)

	c.JSON(
		http.StatusOK, gin.H{
			"code":  code,
			"message": errmsg.GetErrMsg(code),
		},
	)
}

func EditUser(c *gin.Context) {
	var data model.User
	_ = c.ShouldBindJSON(&data)

	code := model.EditUser(&data)

	c.JSON(
		http.StatusOK, gin.H{
			"code":  code,
			"message": errmsg.GetErrMsg(code),
		},
	)
}
